package com.yand.frame.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yand.frame.dao.ActivityRoleMapper;
import com.yand.frame.dao.ActivityRoleMenuMapper;
import com.yand.frame.entity.ActivityMenu;
import com.yand.frame.entity.ActivityRole;
import com.yand.frame.entity.ActivityRoleMenu;
import com.yand.frame.service.RoleService;
import com.yand.frame.utils.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;


@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private ActivityRoleMapper activityRoleMapper;

    @Autowired
    private TreeUtil treeUtil;


    @Autowired
    private ActivityRoleMenuMapper activityRoleMenuMapper;

    @Override
    public PageInfo queryAllRole(ActivityRole role) {

        PageHelper.startPage(role.getPageNum(), role.getPageSize());

        return PageInfo.of(activityRoleMapper.queryRoleList(role));

    }

    @Override
    public ActivityRole getRole(int roleId) {
        return activityRoleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public List<ActivityMenu> getMenuByRoleId(int roleId) {
        List<ActivityMenu> menuList = activityRoleMapper.queryCheckedMenuByRoleId(roleId);
        List<ActivityMenu> menuTreeList = (List<ActivityMenu>)treeUtil.getAllTreeJavaBean(menuList);
        return menuTreeList;
    }

    @Override
    public void addRole(ActivityRole role) {

        activityRoleMapper.insert(role);

        String [] menuIds = role.getMenuIds().split(",");

        List<ActivityRoleMenu> list = new ArrayList<>();

        for(String menuId : menuIds){

            ActivityRoleMenu activityRoleMenu = new ActivityRoleMenu();

            activityRoleMenu.setRoleId(role.getId());

            activityRoleMenu.setMenuId(Integer.parseInt(menuId));

            list.add(activityRoleMenu);
        }
        activityRoleMenuMapper.batchInsert(list);
    }

    @Override
    public void delRole(int roleId) {


        activityRoleMapper.deleteByPrimaryKey(roleId);

        activityRoleMenuMapper.deleteRoleMenuByRoleId(roleId);

    }

    public void updateRole(ActivityRole role){
        activityRoleMapper.updateByPrimaryKeySelective(role);
        activityRoleMenuMapper.deleteRoleMenuByRoleId(role.getId());
        List<ActivityRoleMenu> list = new ArrayList<>();

        for(String menuId : role.getMenuIds().split(",")){
            ActivityRoleMenu activityRoleMenu = new ActivityRoleMenu();

            activityRoleMenu.setRoleId(role.getId());

            activityRoleMenu.setMenuId(Integer.parseInt(menuId));

            list.add(activityRoleMenu);
        }
        activityRoleMenuMapper.batchInsert(list);
    }

}
